package com.beiming.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.beiming.common.utils.HttpContextUtil;
import com.beiming.common.utils.Result;
import com.beiming.common.utils.TokenUtil;
import com.beiming.moudle.auth.entity.BussUserEntity;
import com.beiming.moudle.auth.entity.CustomerUserEntity;
import com.beiming.moudle.auth.entity.UserEntity;
import com.beiming.moudle.auth.service.BussService;
import com.beiming.moudle.auth.service.BussUserService;
import com.beiming.moudle.auth.service.CustomerUserService;
import com.beiming.moudle.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private BussUserService bussUserService;
    @Autowired
    private CustomerUserService customerUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String auth_token = "";
        String buss_token = "";
        String user_token = "";
        String token_type="";
        auth_token =TokenUtil.getRequestToken(request).get("admin_token").toString();
        buss_token =TokenUtil.getRequestToken(request).get("bussiness_token").toString();
        user_token =TokenUtil.getRequestToken(request).get("user_token").toString();
        token_type =TokenUtil.getRequestToken(request).get("token_type").toString();

        switch (token_type) {
            case "bussiness_token" :
               buss_check(buss_token,response);break;
            case  "admin_token" :
                admin_check(auth_token,response);break;
            case  "user_token" :
                 user_check(user_token,response);break;
        }


        return true;
    }

    Boolean admin_check(String token,HttpServletResponse response) throws IOException {

        if (StringUtils.isBlank(token)) {
            setReturn(response, 450, "用户未登录，请先登录");
            //response.sendRedirect(request.getContextPath()+"/");
            return false;
        }
        //1. 根据token，查询用户信息
        UserEntity userEntity = userService.findByToken(token);
        //2. 若用户不存在,
        if (userEntity == null) {
            setReturn(response, 450, "用户不存在");
            return false;
        }
        //3. token失效
        if (userEntity.getExpireTime().isBefore(LocalDateTime.now())) {
            setReturn(response, 450, "用户登录凭证已失效，请重新登录");
            return false;
        }
        System.out.println("token检验成功"+token);
        return true;
    }

    Boolean buss_check(String token,HttpServletResponse response) throws IOException {

        if (StringUtils.isBlank(token)) {
            setReturn(response, 450, "用户未登录，请先登录");
            //response.sendRedirect(request.getContextPath()+"/");
            return false;
        }
        //1. 根据token，查询用户信息
        System.out.println(token);
        BussUserEntity bussUserEntity = bussUserService.findByToken(token);
        //2. 若用户不存在,
        if (bussUserEntity == null) {
            setReturn(response, 450, "用户不存在");
            return false;
        }
        //3. token失效
        if (bussUserEntity.getExpireTime().isBefore(LocalDateTime.now())) {
            setReturn(response, 450, "用户登录凭证已失效，请重新登录");
            return false;
        }
        System.out.println("token检验成功"+token);
        return true;
    }

    Boolean user_check(String token,HttpServletResponse response) throws IOException {

        if (StringUtils.isBlank(token)) {
            setReturn(response, 450, "用户未登录，请先登录");
            //response.sendRedirect(request.getContextPath()+"/");
            return false;
        }
        //1. 根据token，查询用户信息
        System.out.println(token);
        CustomerUserEntity customerUserEntity = customerUserService.findByToken(token);
        //2. 若用户不存在,
        if (customerUserEntity == null) {
            setReturn(response, 450, "用户不存在");
            return false;
        }
        //3. token失效
        if (customerUserEntity.getExpireTime().isBefore(LocalDateTime.now())) {
            setReturn(response, 450, "用户登录凭证已失效，请重新登录");
            return false;
        }
        System.out.println("token检验成功"+token);
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    private static void setReturn(HttpServletResponse response, int status, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setStatus(400);
        response.setContentType("application/json;charset=utf-8");
        Result build = Result.build(status, msg);
        String json = JSON.toJSONString(build);
        httpResponse.getWriter().print(json);
    }

}
